#include "server_thread.h"
#include "log_utils.h"
#include "database.h" // ✅ 确保引入数据库头文件

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8888

int main() {
    // 初始化数据库
    if (!Database::initialize()) {
        std::cerr << "数据库初始化失败，服务器终止\n";
        return -1;
    }

    int serverSock = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSock < 0) {
        std::cerr << "无法创建 socket\n";
        return 1;
    }

    sockaddr_in serverAddr {};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);

    if (bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        std::cerr << "绑定失败\n";
        return 1;
    }

    if (listen(serverSock, 5) < 0) {
        std::cerr << "监听失败\n";
        return 1;
    }

    std::cout << "服务器启动，端口: " << PORT << "\n";
    write_log("服务器已启动");

    while (true) {
        sockaddr_in clientAddr;
        socklen_t len = sizeof(clientAddr);
        int clientSock = accept(serverSock, (sockaddr*)&clientAddr, &len);
        if (clientSock < 0) continue;

        ThreadArgs* args = new ThreadArgs{clientSock, clientAddr};
        pthread_t tid;
        pthread_create(&tid, nullptr, handle_client, args);
        pthread_detach(tid);
    }

    close(serverSock);
    return 0;
}